import { SET_GOODS_SKU_LIST, SET_GOODS_PROPS, SET_GOODS_INFO, SET_GOODS_LIST, INIT_GOODS_INFO } from './mutation_types.js'
import * as service from '../../api/menu.js'
let goodsInfo = {
  shopId: "",
  catId: "",
  title: "",
  price: "",
  isRecommend: "",
  image: "",
  desc: "",
  skuList: [],
  props: [],
}
const menus = {
  state: {
    goodList: [],
    shopId: "",
    catId: "",
    title: "",
    price: "",
    isRecommend: "",
    image: "",
    desc: "",
    skuList: [],
    props: [],
    goodsInfo: JSON.parse(JSON.stringify(goodsInfo))
  },
  mutations: {
    [SET_GOODS_SKU_LIST]: (state, list) => {
      state.goodsInfo.skuList = list
    },
    [SET_GOODS_PROPS]: (state, list) => {
      state.goodsInfo.props = list
    },
    [SET_GOODS_LIST]: (state, list) => {
      state.goodList = list
    },
    [SET_GOODS_INFO]: (state, data) => {
      // debugger
      if (data.skuList && !Array.isArray(data.skuList)) {
        data.skuList = [data.skuList]
      }
      for (const key in data) {
        state.goodsInfo[key] = data[key] || null
      }
    },
    [INIT_GOODS_INFO]: (state, data) => {
      state.goodsInfo = JSON.parse(JSON.stringify(goodsInfo))
    },
  },
  actions: {
    async postGoods({ commit, getters }, params) {
      let shopId = getters.shopId
      let res = await service.postGoods(params, shopId)
      if (!res.code) commit(INIT_GOODS_INFO)
      return res
    },
    async getGoods({ commit, getters }, params) {
      let shopId = getters.shopId
      let { data } = await service.getGoods(shopId, params)
      commit(SET_GOODS_LIST, data)
      return data
    },
    async deleteGoods({ commit }, id) {
      let res = await service.deleteGoods(id)
      return res
    },
    async putGoods({ commit }, params) {
      let res = await service.putGoods(params)
      if (!res.code) commit(INIT_GOODS_INFO)
      return res
    }
  }
}
export default menus
